# -*- coding: utf-8 -*-
# @Time    : 2023/2/21 17:25
# @Author  : HeAlec
# @FileName: sttrace.py
# @Desc: description
# @blogs ：https://segmentfault.com/u/alec_5e8962e4635ca
from utils import getMaxError, getError4GPS


def STTrace(points, max_buffer_size, mode):
    buffer = []
    buffer.append([points[0], 0])
    max_err = 0
    if max_buffer_size > 2:
        buffer.append([points[1], 0])
        for i in range(2, len(points)):
            buffer.append([points[i], 0])
            st = buffer[len(buffer) - 3]
            en = buffer[len(buffer) - 1]
            buffer[len(buffer) - 2][1] = getError4GPS(buffer[len([buffer])][0], st[0], en[0], mode)
            if len(buffer) > max_buffer_size:
                start = buffer[0]
                to_remove = buffer[len(buffer) - 1]
                min_idx = 1
                k = 1
                for i in range(1, len(buffer) - 1):
                    p = buffer[i]
                    if to_remove == buffer[len(buffer) - 1] or p[1] < to_remove[1]:
                        to_remove = p
                        k += 1
                if min_idx - 1 > 0:
                    buffer[min_idx - 1][1] = getError4GPS(buffer[min_idx - 1][0], buffer[min_idx - 2][0],
                                                        buffer[min_idx + 1][0], mode)
                if min_idx + 1 < len(buffer) - 1:
                    buffer[min_idx + 1][1] = getError4GPS(buffer[min_idx + 1][0], buffer[min_idx - 1][0],
                                                        buffer[min_idx + 2][0], mode)
                buffer.remove(to_remove)

    else:
        buffer.append([points[len(points) - 1], 0])
    idx = []
    for i in range(len(buffer)):
        idx.append(points.index(buffer[i][0]))
    idx.sort()

    for i in range(len(idx) - 1):
        st = idx[i]
        en = idx[i + 1]
        _, err = getMaxError(st, en, points, mode)
        max_err = max(max_err, err)
    return None, idx, max_err
